package org.wwy.demo.excel.graph;

import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xssf.usermodel.XSSFChart;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFSheet;

/**
 *
 */
public class GraphInstance {

    private XDDFLineChartData leftdata;

    private XSSFChart chart;

    /**
     * 表单
     */
    private XSSFSheet sheet;

    /**
     * 图区域
     */
    private CellRangeAddress graphRange;

    private GraphInstance(){

    }

    /**
     *
     * @param sheet
     * @param graphRange
     * @param title
     */
    public GraphInstance(XSSFSheet sheet, CellRangeAddress graphRange,String title) {
        this.sheet = sheet;
        this.graphRange = graphRange;

        XSSFDrawing drawing = sheet.createDrawingPatriarch();
        XSSFClientAnchor xssfClientAnchor = drawing.createAnchor(0, 0, 0, 0,
                graphRange.getFirstColumn(),
                graphRange.getFirstRow(),
                graphRange.getLastColumn(),
                graphRange.getLastRow());
        chart = drawing.createChart(xssfClientAnchor);
        XDDFChartLegend legend = chart.getOrAddLegend();
        legend.setPosition(LegendPosition.TOP_RIGHT);

        // Use a category axis for the bottom axis.
        XDDFCategoryAxis bottomAxis = chart.createCategoryAxis(AxisPosition.TOP);//底部X轴
//        bottomAxis.setTitle("交易情况汇总");

        XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);//左侧Y轴
        leftAxis.setTitle(title);
        leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);

        leftdata = (XDDFLineChartData) chart.createData(ChartTypes.LINE, bottomAxis, leftAxis);

    }

    /**
     * @param desc
     * @param dataRange
     */
    public void drawLineChart(String desc, CellRangeAddress dataRange) {
        draw(desc,dataRange,null);
    }

    public void drawLineChart(String desc,CellRangeAddress dataRange, CellRangeAddress xRange) {
        //填充数据
        XDDFCategoryDataSource xs = XDDFDataSourcesFactory.fromStringCellRange(sheet, xRange);
        draw(desc,dataRange,xs);
    }

    public void draw(String desc, CellRangeAddress dataRange,
                              XDDFDataSource<String> xddfDataSource) {
        XDDFDataSource<String> finalXs = xddfDataSource;
        XDDFNumericalDataSource<Double> ys = XDDFDataSourcesFactory.fromNumericCellRange(sheet, dataRange);//纵轴为各个数据
        XDDFLineChartData.Series series = (XDDFLineChartData.Series) leftdata.addSeries(finalXs, ys);
        series.setTitle(desc, null);
        series.setSmooth(false);
        series.setMarkerStyle(MarkerStyle.DASH);

        chart.plot(leftdata);
    }
}
